package service

import (
	"time"

	pb "gitee.com/hakwolf/taibak/internal/modules/rpc/proto"
	"gitee.com/hakwolf/taibak/internal/modules/utils"
	//_ "github.com/mattn/go-adodb"
	log "github.com/sirupsen/logrus"
	"golang.org/x/net/context"
	"google.golang.org/grpc/keepalive"
)

type Server struct{}

var keepAlivePolicy = keepalive.EnforcementPolicy{
	MinTime:             10 * time.Second,
	PermitWithoutStream: true,
}

var keepAliveParams = keepalive.ServerParameters{
	MaxConnectionIdle: 30 * time.Second,
	Time:              30 * time.Second,
	Timeout:           3 * time.Second,
}

func (s Server) Run(ctx context.Context, req *pb.TaskRequest) (*pb.TaskResponse, error) {
	defer func() {
		if err := recover(); err != nil {
			log.Error(err)
		}
	}()
	log.Infof("execute cmd start: [id: %d cmd: %s]", req.Id, req.Command)
	output, err := utils.ExecShell(ctx, req.Command)
	resp := new(pb.TaskResponse)
	resp.Output = output
	if err != nil {
		resp.Error = err.Error()
	} else {
		resp.Error = ""
	}
	log.Infof("execute cmd end: [id: %d cmd: %s err: %s]", req.Id, req.Command, resp.Error)

	return resp, nil
}

func (s Server) DbRun(ctx context.Context, req *utils.DbTaskRequest) (*utils.DbTaskResponse, error) { //req *pb.DbTaskRequest
	defer func() {
		if err := recover(); err != nil {
			log.Error(err)
		}
	}()

	err := utils.ExecDb(ctx, req)

	resp := new(utils.DbTaskResponse)
	//resp.Output = output
	if err != nil {
		resp.Error = err.Error()
	} else {
		resp.Error = ""
	}

	log.Infof("execute cmd start: [id: %d dbname: %s port %d]", req.Id, req.Dbname, req.Port)
	return resp, nil

	/*	log.Infof("execute cmd start: [id: %d cmd: %s]", req.Id, req.Command)
		output, err := utils.ExecShell(ctx, req.Command)
		resp := new(pb.TaskResponse)
		resp.Output = output
		if err != nil {
			resp.Error = err.Error()
		} else {
			resp.Error = ""
		}
		log.Infof("execute cmd end: [id: %d cmd: %s err: %s]", req.Id, req.Command, resp.Error)*/
}
